import axios from 'axios'
import { ElNotification } from 'element-plus'

const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 30000000
})


service.interceptors.request.use(
  config => {
    config.headers = {}
    config.headers['Content-Type'] = 'application/json'
    return config
  },
  error => {
    console.log(error);
    Promise.reject(error)
  }
)

service.interceptors.response.use(
  response => {
    const code = response.status
    const data = response.data
    // const message = response.message
    if (code < 200 || code > 300) {
      ElNotification({
        title: 'Error',
        message: '网络错误',
        type: 'error',
      })
      return Promise.reject('error')
    }
    // else if (typeof data.code == 'number' || data.code !== 200) {
    //   if (data.code == 401) {
    //     location.reload() // 为了重新实例化vue-router对象 避免bug
    //     return Promise.reject('error')
    //   }
    //   ElNotification({
    //     title: 'Error',
    //     message: data.msg
    //   })
    //   return data
    // }
    else if (response.config.responseType === 'arraybuffer' || response.config.responseType === 'blob') {
      // let url = ``
    } else {
      return data
    }
  },
  error => {
    let code = 0
    try {
      code = error.response.data.status
    } catch (e) {
      if (error.toString().indexof('Error: Network Error') !== -1) {
        ElNotification({
          title: '网络请求错误',
          type: 'error'
        })
        return Promise.reject(error)
      }
      return Promise.reject(error)
    }
  }
)

export default service
